#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"../include/main.h"
#include"../include/bst.h"
#include"../include/deldir.h"
#include"../include/mount_vfs.h"
#include"../include/narrtree.h"
#include"../include/hash.h"
#include"../include/vfs_errorcodes.h"
#include"../include/create_vfs.h"

void deldir(char path[])
{
	fdesc *mkdescd;
	ntree *temphead;
	char temp[MAX_PATH],*r;
	char *dname,*pchh,invalid_char[]={'/'};
	int i=0,listd;
	char *t;
	llist *list;
	char *pch=strrchr(path,'/');
	if(pch != NULL)
	pch++;
	if(!strcmp(path,"/"))
	{
		
		if(head != NULL)// && head->first != NULL)
		{
			if(head->first != NULL)
				printf("%s_FAILURE_%s\n",glb_command,ERR_VFS_DELETEDIR_02);
			else
			{
				mkdescd=(fdesc *)malloc(sizeof(fdesc));
				strcpy(mkdescd->filepath,"/");
				strcpy(mkdescd->filename,"/");
				mkdescd->filetype=1;
				mkdescd->file_size=0;
				mkdescd->blk_num=0;
				head=delete_ntree(head,mkdescd);
				listd=deletion(mkdescd);
				local_used_fd--;
				printf("deletedir_SUCCESS\n");
			}
		}
		else if(mounted==0)
			printf("%s_FAILURE %s\n",glb_command,ERR_VFS_DELETEDIR_04);
		else
			printf("%s_FAILURE %s\n",glb_command,ERR_VFS_DELETEDIR_01);
	}
	else
	{
	if(mounted==0)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_DELETEDIR_04);
	else
	{
		while(path[i]!='\0')
		{
			temp[i]=path[i];
			i++;
		}
		temp[i]='\0';
		r = strrchr(temp,'/');
		if(r != NULL)
		{
			r++;
			if(*r == '\0')
			{
			temp[i-1] = '\0';
			path[i-1] = '\0';
			}
		}
		pchh = strtok (temp,"/");
		while (pchh != NULL)
		 {
			dname=pchh;
		 	pchh = strtok (NULL, "/");
		 }
		mkdescd=(fdesc *)malloc(sizeof(fdesc));
		strcpy(mkdescd->filepath,path);
		strcpy(mkdescd->filename,dname);
		mkdescd->filetype=1;
		mkdescd->file_size=0;
		mkdescd->blk_num=0;
		list=find(mkdescd);
		if(list != NULL)
		{
			if(list->desc->filetype==0)
				printf("%s_FAILURE %s\n",glb_command,ERR_VFS_DELETEDIR_01);
			else
			{
				temphead=delete_ntree(head,mkdescd);
				if(temphead != NULL)
				{
					head=temphead;
					listd=deletion(mkdescd);
					if(listd==0)
						printf("%s_FAILURE %s\n",glb_command,ERR_VFS_DELETEDIR_01);
					else
					{
						local_used_fd--;
						printf("deletedir_SUCCESS\n");
					}
				}
				free(mkdescd);
			}
		}
	}
	}
}
